<template>
  <a-card title="住户信息管理" style="width: 400px">
    <template #extra>
      <a-select v-model:value="selectBuild" style="width: 150px" :options="buildsOption" @change="handleChange" />
    </template>
    <a-table size="small" bordered :data-source="houseList" :columns="columns" :pagination="pagination"
      @change="handlePaginationChange" style="margin-bottom: 16px;">
      //column: 当前列的配置信息,
      text: 当前单元格的值,
      record: 当前行的完整数据
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'doorNumText'">
          <a-tag color="red">{{ text }}</a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <a-button type="link" @click="edit(record)">编辑</a-button>
        </template>
      </template>
    </a-table>
  </a-card>
  <FormInfo :formData="formData" :formOpen="formOpen" @onClose="formOpen = false" @onSuccess="handleFormSuccess" />
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { getBuildings, getHouseholdsByUnit, getHousehold, getUnitsByBuilding } from '@/api/api'
import FormInfo from './FormInfo.vue'

// 状态管理
const selectBuild = ref('')
const buildsOption = ref([])
const formData = ref({})  //编辑表单数据
const formOpen = ref(false)//控制编辑弹窗状态
const loading = ref(false)//表格加载状态
const houseList = ref([])//住户列表数据

// 分页配置：使用reactive定义响应式对象
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 8,
  size: 'small',
  showSizeChanger: false,
  showQuickJumper: false
})

// 表格列配置
const columns = [
  { title: '门牌号', dataIndex: 'doorNumText', align: 'center', width: '30%' },
  { title: '业主姓名', dataIndex: 'owner_name', align: 'center', width: '40%' },
  { title: '操作', dataIndex: 'operation', align: 'center', width: '30%' }
]

// 组件挂载时初始化加载楼栋列表
onMounted(async () => {
  const res = await getBuildings()
  if (res?.code === 200) {
    buildsOption.value = res.data.map(item => ({
      value: item.id,
      label: item.name
    }))
  }
})

// 加载单元和住户信息
const handleChange = async (buildId) => {
  try {
    //获取该楼栋的所有单元
    const res = await getUnitsByBuilding(buildId)
    if (res?.code === 200) {
      houseList.value = []
      // 遍历每个单元，获取住户信息
      for (const unit of res.data) {
        const householdsRes = await getHouseholdsByUnit(unit.id)
        if (householdsRes?.code === 200) {
          const households = householdsRes.data.map(item => ({
            ...item,
            // 生成门牌号：将单元号转为字符串,在字符串前面补0，直到长度为2
            doorNumText: `${item.floor_num}${unit.number.toString().padStart(2, '0')}`,
            // Number() 转换为数字,sortKey：用于排序
            sortKey: Number(`${item.floor_num}${unit.number.toString().padStart(2, '0')}`)
          }))
          houseList.value.push(...households)
        }
      }
      // 按楼层和房间号排序:sort() 方法会遍历数组,比较每两个元素的 sortKey
      houseList.value.sort((a, b) => a.sortKey - b.sortKey)
      // 更新分页
      pagination.total = houseList.value.length
      pagination.current = 1
    }
  } catch (error) {
    message.error('加载数据失败')
  }
}

// 编辑住户信息
const edit = async (record) => {
  const res = await getHousehold(record.id)
  if (res?.code === 200) {
    formData.value = res.data
    formOpen.value = true
  }
}

// 处理分页变化
const handlePaginationChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
}

// 处理表单提交成功
const handleFormSuccess = (updatedData) => {
  // 更新表格中对应住户的业主名称
  const index = houseList.value.findIndex(item => item.id === updatedData.id)
  if (index !== -1) {
    houseList.value[index].owner_name = updatedData.owner_name
  }
}
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 24px;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 4px 8px;
  height: 32px;
}

:deep(.ant-table-thead > tr > th) {
  padding: 4px 8px;
  height: 32px;
}

:deep(.ant-btn) {
  padding: 0 4px;
  height: 24px;
  line-height: 24px;
}

:deep(.ant-tag) {
  margin: 0;
  padding: 0 4px;
  line-height: 20px;
}

:deep(.ant-table-pagination) {
  margin: 8px 0;
}
</style>